package user

import (
	"context"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/common/utils"
	"git.myscrm.cn/golang/stark/v4"
	"gorm.io/gorm"
	"time"
)

type CommonUserDataRepository struct {
}

func NewCommonUserDataRepository() CommonUserDataRepoIface {
	return &CommonUserDataRepository{}
}

func (r *CommonUserDataRepository) GetInfoByAccount(ctx context.Context, tenantCode, account string) (*CommonUserInfoBo, error) {
	db := stark.MySQLConn.Get(ctx)
	commonUserInfoBo := &CommonUserInfoBo{}
	err := db.Table(CommonUserData{}.TableName()).Where("tenant_code =? and user_code = ? and is_deleted = 0 ", tenantCode, account).First(&commonUserInfoBo).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return commonUserInfoBo, nil
}

func (r *CommonUserDataRepository) GetInfoByAccountAndPassword(ctx context.Context, tenantCode, account, password string, isNeedMd5 bool) (*CommonUserInfoBo, error) {
	db := stark.MySQLConn.Get(ctx)
	passwordMd5 := ""
	if isNeedMd5 {
		passwordMd5 = utils.Md5(password)
	} else {
		passwordMd5 = password
	}

	commonUserInfoBo := &CommonUserInfoBo{}
	err := db.Table(CommonUserData{}.TableName()).Where("tenant_code =? and user_code = ? and password=? and is_deleted = 0 ", tenantCode, account, passwordMd5).First(&commonUserInfoBo).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return commonUserInfoBo, nil
}

func (r *CommonUserDataRepository) GetInfoByUid(ctx context.Context, uid string) (*CommonUserInfoBo, error) {
	db := stark.MySQLConn.Get(ctx)
	commonUserInfoBo := &CommonUserInfoBo{}
	err := db.Table(CommonUserData{}.TableName()).Where("uid = ? and is_deleted = 0", uid).First(&commonUserInfoBo).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return commonUserInfoBo, nil
}

// 获取绑定用户详情
func (r *CommonUserDataRepository) GetInfoWithBind(ctx context.Context, condition map[string]interface{}) (*CommonUserInfoBo, error) {
	db := stark.MySQLConn.Get(ctx)

	//commonUserBind := &mysql.CommonUserBind{}
	//if mpOpenid, ok := condition["mp_openid"]; ok {
	//	delete(condition, "mp_openid")
	//	condition["user_uid"] =
	//	err := db.Where("mp_openid =?", mpOpenid).Order("created_time desc").First(&commonUserBind).Error
	//	if err != nil && err != gorm.ErrRecordNotFound {
	//		return nil, err
	//	}
	//}
	commonUserInfoBo := &CommonUserInfoBo{}
	err := db.Select(CommonUserData{}.TableName() + ".*,common_user_bind.mp_openid,common_user_bind.unionid as mp_union_id").Table(CommonUserData{}.TableName()).Joins("inner JOIN common_user_bind ON " + CommonUserData{}.TableName() + ".uid = common_user_bind.common_user_data_uid").Where(condition).Where("common_user_data.is_deleted = 0 and common_user_bind.is_deleted = 0").Order("common_user_bind.created_time desc").First(&commonUserInfoBo).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return commonUserInfoBo, nil
}

func (r *CommonUserDataRepository) GetInfoLeftJoinBind(ctx context.Context, condition map[string]interface{}) (*CommonUserInfoBo, error) {
	db := stark.MySQLConn.Get(ctx)
	commonUserInfoBo := &CommonUserInfoBo{}
	err := db.Select(CommonUserData{}.TableName() + ".*,common_user_bind.mp_openid,common_user_bind.unionid as mp_union_id").Table(CommonUserData{}.TableName()).Joins("left JOIN common_user_bind ON " + CommonUserData{}.TableName() + ".uid = common_user_bind.common_user_data_uid").Where(condition).Where("common_user_data.is_deleted = 0").Order("created_time desc").First(&commonUserInfoBo).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return commonUserInfoBo, nil
}

func (r *CommonUserDataRepository) GetInfo(ctx context.Context, condition map[string]interface{}, orderBy string) (*CommonUserData, error) {
	db := stark.MySQLConn.Get(ctx)
	commonUserData := &CommonUserData{}
	err := db.Where(condition).Where("is_deleted = 0").Order(orderBy).First(&commonUserData).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return commonUserData, nil
}

// 根据手机号和租户不为空，查询用户记录
func (r *CommonUserDataRepository) GetUserInfoByMobileAndNotTenantCode(ctx context.Context, mobile string, orderBy string) (*CommonUserData, error) {
	db := stark.MySQLConn.Get(ctx)
	commonUserData := &CommonUserData{}
	err := db.Where("mobile_phone = ? and tenant_code != '' ", mobile).Where("is_deleted = 0").Order(orderBy).First(&commonUserData).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return commonUserData, nil
}

// 根据手机号获取非付费用户
func (r *CommonUserDataRepository) GetUserInfoByMobileNoPay(ctx context.Context, mobile string, orderBy string) (*CommonUserData, error) {
	db := stark.MySQLConn.Get(ctx)
	commonUserData := &CommonUserData{}
	err := db.Where("mobile_phone = ? and tenant_code = '' and tenant_user_uid = '' ", mobile).Where("is_deleted = 0").Order(orderBy).First(&commonUserData).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return commonUserData, nil
}

// 获取列表数据
func (r *CommonUserDataRepository) GetList(ctx context.Context, condition map[string]interface{}, page, pagesize int, orderBy string) (int64, []*CommonUserData, error) {
	db := stark.MySQLConn.Get(ctx)

	commonUserDataList := []*CommonUserData{}
	var count int64 = 0
	if page < 1 {
		page = 1
	}
	if pagesize < 1 {
		pagesize = 10
	}
	offset := (page - 1) * pagesize

	query := db.Table(CommonUserData{}.TableName()).Where(condition)
	err := query.Count(&count).Error
	if err != nil {
		return 0, nil, err
	}
	query = query.Offset(offset).Limit(pagesize).
		Find(&commonUserDataList)
	if orderBy != "" {
		query = query.Order(orderBy)
	}
	err = query.Error
	if err != nil {
		return 0, nil, err
	}
	return count, commonUserDataList, nil
}

// 更新数据
func (r *CommonUserDataRepository) Update(ctx context.Context, data, condition map[string]interface{}) (bool, error) {
	db := stark.MySQLConn.Get(ctx)

	err := db.Model(&CommonUserData{}).Where(condition).Updates(data).Error
	if err != nil {
		return false, err
	}
	return true, nil
}

// 插入数据
func (r *CommonUserDataRepository) Insert(ctx context.Context, commonUserData *CommonUserData) (bool, error) {
	db := stark.MySQLConn.Get(ctx)

	err := db.Save(commonUserData).Error
	if err != nil {
		return false, err
	}

	return true, nil
}

// 逻辑删除数据
func (r *CommonUserDataRepository) Delete(ctx context.Context, condition map[string]interface{}) (bool, error) {
	updateData := map[string]interface{}{}
	updateData["is_deleted"] = 1
	updateData["modified_time"] = time.Now()
	db := stark.MySQLConn.Get(ctx)

	err := db.Model(&CommonUserData{}).Where(condition).Updates(updateData).Error
	if err != nil {
		return false, err
	}
	return true, nil
}

func (r *CommonUserDataRepository) GetUserIno(ctx context.Context, condition map[string]interface{}) (*CommonUserData, error) {
	db := stark.MySQLConn.Get(ctx)
	commonUserData := CommonUserData{}
	err := db.Table(commonUserData.TableName()).Where(condition).First(&commonUserData).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}
	return &commonUserData, nil
}

func (r *CommonUserDataRepository) GetUserActionRightInfos(ctx context.Context, condition map[string]interface{}) ([]*CommonUserActionRightInfos, error) {
	db := stark.MySQLConn.Get(ctx)
	commonUserActionRightInfos := []*CommonUserActionRightInfos{}
	err := db.Where(condition).Find(&commonUserActionRightInfos).Error
	return commonUserActionRightInfos, err
}

func (r *CommonUserDataRepository) GetUserRoleRelation(ctx context.Context, condition map[string]interface{}) ([]*CommonUserRoleRelation, error) {
	db := stark.MySQLConn.Get(ctx)
	commonUserRoleRelation := []*CommonUserRoleRelation{}
	err := db.Where(condition).Find(&commonUserRoleRelation).Error
	return commonUserRoleRelation, err
}

func (r *CommonUserDataRepository) CreateUserActionRightInfos(ctx context.Context, tx *gorm.DB, commonUserActionRightInfos []*CommonUserActionRightInfos) error {
	err := tx.Create(&commonUserActionRightInfos).Error
	return err
}

func (r *CommonUserDataRepository) DelUserActionRightInfos(ctx context.Context, tx *gorm.DB, tenantCode string, tenantUserUid string) error {
	err := tx.Where("tenant_code = ? and tenant_user_uid = ?", tenantCode, tenantUserUid).Delete(&CommonUserActionRightInfos{}).Error
	return err
}

func (r *CommonUserDataRepository) DelUserRoleRelation(ctx context.Context, tx *gorm.DB, tenantCode string) error {
	err := tx.Where("tenant_code = ?", tenantCode).Delete(&CommonUserRoleRelation{}).Error
	return err

}

func (r *CommonUserDataRepository) CreateUserRoleRelation(ctx context.Context, tx *gorm.DB, commonUserRoleRelation []*CommonUserRoleRelation) error {
	err := tx.Create(&commonUserRoleRelation).Error
	return err
}

func (r *CommonUserDataRepository) PersonalUserToTenantRecordWrite(ctx context.Context, commonPersonalUserToTenantRecordPo *CommonPersonalUserToTenantRecordPo) error {
	db := stark.MySQLConn.Get(ctx)
	err := db.Save(commonPersonalUserToTenantRecordPo).Error
	return err
}
